<template>
  <fks-dialog
    :visible="visible"
    width="1200px"
    top="8vh"
    append-to-body
    custom-class="user-group-select"
    :before-close="closeDialog"
  >
    <div slot="title">
      <i class="fks-icon-user" />
      <span>{{ LANG.USER_GROUP }}</span>
    </div>

    <fks-row>
      <fks-input
        v-model="searchKey"
        :placeholder="LANG.SEARCH_PLACEHOLDER"
        suffix-icon="fks-icon-search"
        @keyup.enter.native="searchUserGroup"
      />
    </fks-row>

    <fks-row class="user-group-transfer-container" :gutter="64">
      <!-- 左侧 -->
      <fks-col :span="12">
        <div class="right-button">
          <fks-button
            size="small"
            plain
            icon="fks-icon-select-all"
            class="second-button"
            v-show="groupType != 'org'"
            @click="chooseAll"
          >
            {{ LANG.SELECT_ALL }}
          </fks-button>
        </div>
        <fks-tabs
          v-model="editableTabsValue"
          class="user-group-transfer-tabs"
          type="card"
        >
          <!-- 用户组列表 -->
          <fks-tab-pane :label="LANG.USER_GROUP_LIST" name="first" />
          <!-- 最近添加 -->
          <!-- <fks-tab-pane :label="LANG.RECENTLY_ADD" name="second">
          </fks-tab-pane> -->
        </fks-tabs>
        <div class="user-group-left-table" v-if="groupType != 'org'">
          <fks-table
            v-loading="loading"
            border
            :data="leftTableForShow"
            height="400px"
            @row-click="addToRight"
            @sort-change="sortHandler"
          >
            <fks-table-column
              prop="name"
              sortable="custom"
              :label="LANG.NAME"
              min-width="50%"
            />
            <fks-table-column prop="code" :label="LANG.CODE" min-width="50%" />
          </fks-table>
          <div class="user-group-left-page">
            <fks-pagination
              v-if="editableTabsValue == 'first'"
              :total="total"
              :pager-count="5"
              :page-sizes="[25, 50, 100, 200]"
              :page-size="pageSize"
              layout="prev, pager, next,total, sizes"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
            <fks-pagination
              v-if="editableTabsValue == 'second'"
              :total="leftTableForShow.length"
              layout="total"
            />
          </div>
        </div>
        <div class="user-group-left-tree" v-if="groupType == 'org'">
          <fks-tree
            :data="leftTreeForShow"
            :props="treeProps"
            @node-click="handleNodeClick"
            default-expand-all
            :filter-node-method="filterTreeNode"
            ref="tree"
          >
            <template slot-scope="{ node, data }">
              <span>{{ data.content.name }}</span>
            </template>
          </fks-tree>
        </div>
      </fks-col>

      <!-- 右侧 -->
      <fks-col :span="12">
        <div class="right-button">
          <fks-button
            size="small"
            plain
            icon="fks-icon-reset"
            class="second-button"
            @click="clearChosed"
          >
            {{ LANG.CLEAR }}
          </fks-button>
        </div>
        <div class="user-group-right-transfer">
          <div class="user-group-right-transfer__title">
            {{ LANG.CHOOSED }}
          </div>
          <div class="user-group-right-transfer__content">
            <fks-table
              v-loading="loading"
              border
              stlye="width:100%"
              :data="chosedListForShow"
              height="437px"
              header-row-class-name="my-table-head"
              row-class-name="my-table-row"
              @row-click="deleteChosed"
            >
              <fks-table-column
                prop="name"
                sortable="custom"
                :label="LANG.NAME"
                min-width="50%"
              />
              <fks-table-column
                prop="code"
                :label="LANG.CODE"
                min-width="50%"
              />
            </fks-table>
          </div>
        </div>
      </fks-col>
    </fks-row>

    <!-- 底部 -->
    <div slot="footer">
      <fks-button icon="fks-icon-check" primary @click="saveChosed">
        {{ LANG.CONFIRM }}
      </fks-button>
    </div>
  </fks-dialog>
</template>
<script>
import { getUserGroup, getOrgTree } from '../api'
import { unique } from '@/utils/array'
export default {
  name: 'AddUserGroup',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    groupType: {
      type: String,
      default: 'org'
    },
    multiple: {
      type: Boolean,
      default: true
    },
    multipleLimit: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      GROUPTYPE_POST: 1,
      GROUPTYPE_ORG: 2,

      sort: '',
      searchKey: '',
      filterKey: '',
      editableTabsValue: 'first',

      loading: false,

      leftTable: [], //左侧非org显示列表型
      leftTree: [], //左侧是org时显示树形
      chosedList: [],

      // 分页相关
      pageNo: 1,
      pageSize: 25,
      total: 0,

      treeProps: {
        children: 'children',
        label: 'id'
      }
    }
  },
  computed: {
    //当前门户
    portal() {
      return this.$store.state.portal
    },
    chosedListForShow() {
      return this.filterListForShow(this.chosedList)
    },
    leftTableForShow() {
      let arr = []
      switch (this.editableTabsValue) {
        case 'second':
          arr = this.$storage.get('latestUserGroup')
            ? JSON.parse(this.$storage.get('latestUserGroup'))
            : []
          break
        default:
          arr = this.leftTable
          break
      }
      return this.filterListForShow(arr)
    },
    leftTreeForShow() {
      let arr = this.leftTree
      return arr
    },
    /**
     * @description: 魔法值转换
     */
    type() {
      switch (this.groupType) {
        case 'org':
          return this.GROUPTYPE_ORG
        default:
          return this.GROUPTYPE_POST
      }
    }
  },
  watch: {
    filterKey(val) {
      if (this.groupType == 'org') {
        this.$refs.tree.filter(val)
      }
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    /**
     * @description: 过滤树
     */
    filterTreeNode(value, data) {
      if (!value) return true
      return data.content?.name?.indexOf(value) > -1
    },
    /**
     * @description: 过滤表单
     */
    filterListForShow(arr) {
      return arr.filter((item) => {
        return (
          item.name.indexOf(this.filterKey) >= 0 &&
          item.type == this.type &&
          this.portal.id == item.portalId
        )
      })
    },
    closeDialog() {
      this.$emit('update:visible', false)
    },

    /**
     * @description: 选择完毕并提交
     *               先更新storage，然后回调addMembers方法
     *               更新时做下去重并保持顺序
     */
    saveChosed() {
      let arr = this.$storage.get('latestUserGroup')
        ? JSON.parse(this.$storage.get('latestUserGroup'))
        : []
      let newArr = this.chosedList.concat(arr).slice(0, 20)

      for (let i = 0; i < newArr.length; i++) {
        for (let j = i + 1; j < newArr.length; j++) {
          if (newArr[i].id == newArr[j].id) {
            newArr.splice(j, 1)
            j--
          }
        }
      }

      this.$storage.set('latestUserGroup', JSON.stringify(newArr))

      this.$emit('change', this.chosedList)
    },

    /**
     * @description: 树节点点击后加入右侧
     */
    handleNodeClick(data) {
      let { portalId, id, name } = data.content
      let row = { code: data.id, portalId, id, name, type: this.type }
      this.addToRight(row)
    },
    /**
     * @description: 全选
     */
    chooseAll() {
      this.chooseFunc(this.leftTableForShow)
    },
    /**
     * @description: 全选时倒序加入，达到正序的效果
     */
    chooseFunc(arr) {
      for (let i = arr.length - 1; i >= 0; i--) {
        this.addToRight(arr[i])
      }
    },

    /**
     * @description: 勾选用户组
     */
    addToRight(row) {
      // 左右穿梭框数据的添加
      var result = this.chosedList.some(function (item) {
        // 采用some为了避免查询结果相同的对象因指针不同而可以再次添加
        if (item.id == row.id) {
          return true
        }
      })

      if (result) {
        return false
      }

      if (!this.multiple) {
        this.chosedList.shift()
        this.chosedList.unshift(row)
        return
      }

      if (
        this.multipleLimit <= 0 ||
        this.chosedList.length < this.multipleLimit
      ) {
        this.chosedList.unshift(row)
      }
    },

    /**
     * @description: 右侧删除
     */
    deleteChosed(row) {
      this.chosedList.splice(this.chosedList.indexOf(row), 1)
    },

    /**
     * @description: 右侧清空
     */
    clearChosed() {
      this.chosedList = []
    },

    /**
     * @description: 表格切换页码、size、排序等
     */
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNo = 1
      this.searchUserGroup()
    },
    handlePageChange(val) {
      this.pageNo = val
      this.searchUserGroup()
    },
    sortHandler(data) {
      this.sort = data.order == 'ascending' ? 'asc' : 'desc'
      this.columnName = data.prop
      this.searchUserGroup()
    },

    /**
     * @description: 获取用户组
     */
    searchUserGroup() {
      this.loading = true
      if (this.groupType == 'org') {
        let data = {
          portalId: this.$store.state.portal.id,
          isAll: false
        }
        getOrgTree(data)
          .then((res) => {
            if (res.status) {
              this.leftTree = res.data
            }
          })
          .finally(() => {
            this.loading = false
            this.filterKey = this.searchKey
          })
        return
      }

      let data = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        portalId: this.$store.state.portal.id,
        searchValue: this.searchKey,
        columnName: this.columnName,
        sort: this.sort,
        type: this.type
      }
      getUserGroup(data)
        .then((res) => {
          if (res.status) {
            this.total = res.data.total
            this.leftTable = res.data.list
          }
        })
        .finally(() => {
          this.loading = false
          this.filterKey = this.searchKey
        })
    },

    initData() {
      this.pageNo = 1
      this.pageSize = 25
      this.searchKey = this.filterKey = ''
      this.editableTabsValue = 'first'
      this.searchUserGroup()
    }
  }
}
</script>

<style lang='scss' scoped>
::v-deep .user-group-select {
  .fks-dialog__body {
    padding: 24px 32px !important;
  }
  .fks-dialog__footer {
    padding-top: 0 !important;
  }
}

.user-group-selector-page {
  text-align: left;
  position: relative;
  display: inline-block;
}

.user-group-selector-page .user-group-out-input .fks-input__inner {
  color: transparent !important;
}

.user-group-selector-input {
  position: relative;
  width: 100%;
}

.fks-dialog__header i:not(.fks-dialog__close) {
  font-size: 20px;
  margin-right: 8px;
}

.fks-dialog__body {
  padding: 0 32px 24px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
  height: -webkit-fit-content;
  height: -moz-fit-content;
  height: fit-content;
  max-height: none !important;
  overflow: hidden !important;
}

.user-group-search {
  margin-bottom: 8px;
}

.right-button {
  position: absolute;
  right: 34px;
  top: 0;
  z-index: 10;
}

.second-button {
  padding: 8px 16px;
  font-size: 12px;
}

.second-button:before {
  padding-right: 4px;
}

.user-group-transfer-container {
  background-color: #fff;
  margin-top: 24px;
  border-top: 1px solid #eee;
  padding-top: 24px;
  .fks-col {
    position: relative;
  }
  ::v-deep .fks-table tr:hover {
    cursor: pointer;
  }
}

.user-group-transfer-tabs {
  ::v-deep .fks-tabs__header {
    margin-bottom: -1px;
  }
  ::v-deep .fks-tabs__item {
    border-bottom: none;
  }
}

.user-group-left-page {
  background-color: #f9f9f9;
  padding: 2px 0 2px 17px;
  border: 1px solid #ddd;
  border-top: 0;
  text-align: right;
}

.user-group-left-tree {
  border: 1px solid #eee;
  border-top: none;
  margin-top: 1px;
  height: 437px;
  overflow-y: scroll;
}

::v-deep .user-group-left-page {
  .btn-next,
  .btn-prev,
  .fks-pager li {
    background-color: transparent;
  }
}

.user-group-right-transfer {
  width: 100%;
  position: relative;
  display: inline-block;
  vertical-align: top;
}

.user-group-right-transfer__title {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-align: left;
  height: 40px;
  color: #999;
  padding-top: 6px;
}

.user-group-right-transfer__content {
  height: calc(100% - 50px);
  border-bottom: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
</style>